package com.risk.ctrl.aspect;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.risk.ctrl.constants.CommonConstant;
import com.risk.ctrl.credit.entity.ApiCallLog;
import com.risk.ctrl.credit.service.IApiCallLogService;
import com.risk.ctrl.entity.base.Result;
import com.risk.ctrl.utils.SpringContextUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.Objects;


/**
 * 系统日志，切面处理类
 *
 * @Author scott
 * @email jeecgos@163.com
 * @Date 2018年1月14日
 */
@Aspect
@Component
public class AutoLogAspect {

    @Resource
    private IApiCallLogService apiCallLogService;

    @Pointcut("@annotation(com.risk.ctrl.annotation.AutoLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Date beginTime = new Date();
        //执行方法
        Object result = point.proceed();

        //保存日志
        saveSysLog(point, beginTime, result);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, Date beginTime, Object obj) {
        ApiCallLog dto = new ApiCallLog();
        dto.setApiType(CommonConstant.ZERO_INT);
        dto.setCallTime(beginTime);
        String result = null;
        if(Objects.nonNull(obj) && Result.class.isAssignableFrom(obj.getClass())){
            Result<?> result1 = ((Result<?>) obj);
            Map<String, Object> resultMap = Maps.newLinkedHashMap();
            resultMap.put("code", result1.getCode());
            resultMap.put("message", result1.getMessage());
            result = JSON.toJSONString(resultMap);
        }
        dto.setCallResult(result);
        //获取request
        HttpServletRequest request = SpringContextUtil.getHttpServletRequest();
        String appKey = request.getHeader("appKey");
        dto.setAppKey(appKey);
        dto.setAppSign(request.getHeader("sign"));
        dto.setCreateTime(beginTime);
        //保存系统日志
        apiCallLogService.save(dto);
    }


}
